/** @odoo-module **/

import { WebClient } from "@web/webclient/webclient";
import { patch } from "@web/core/utils/patch";
import { useService } from "@web/core/utils/hooks";
import { useState } from "@odoo/owl";

patch(WebClient.prototype, {
    setup() {
        super.setup();
        this.layoutConfig = useService("layoutConfig");
        this.actionService = useService("action");
        console.log('[WebClient] Layout config loaded:', this.layoutConfig);
        
        // 如果启用了多标签页，初始化标签页状态
        if (this.layoutConfig.isMultiTabEnabled()) {
            this.tabState = useState({
                tabs: [],
                activeTabId: null,
            });
            this._patchActionService();
        }
    },
    
    _patchActionService() {
        console.log('[WebClient] Patching action service for multi-tab...');
        const originalDoAction = this.actionService.doAction.bind(this.actionService);
        // 保存原始方法的引用
        originalDoAction.__original = originalDoAction;
        
        this.actionService.doAction = async (action, options = {}) => {
            console.log('[WebClient] doAction called:', action, options);
            // 如果启用了多标签页且不是内部调用
            if (this.layoutConfig.isMultiTabEnabled() && !options._isTabManagerCall) {
                console.log('[WebClient] Creating new tab...');
                // 创建新标签页
                const tabId = `tab_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
                
                // 获取 action 的标题 - 改进标题获取逻辑
                let title = 'New Tab';
                if (typeof action === 'object') {
                    // 优先使用 display_name, name，然后尝试从 context 中获取
                    title = action.display_name || 
                           action.name || 
                           (action.context && action.context.menu_name) ||
                           action.xml_id || 
                           action.res_model || 
                           title;
                } else if (typeof action === 'string') {
                    title = action;
                } else if (typeof action === 'number') {
                    // 如果是 action ID，从菜单服务中查找对应的菜单名称
                    title = this._getMenuNameByActionId(action) || `Action ${action}`;
                }
                
                console.log('[WebClient] Tab title:', title);
                
                // 添加标签页
                this.addTab({
                    id: tabId,
                    title: title,
                    action: action,
                    options: { ...options, _isTabManagerCall: true },
                });
                
                console.log('[WebClient] Current tabs:', this.tabState.tabs.length);
                console.log('[WebClient] Active tab:', this.tabState.activeTabId);
                
                return Promise.resolve();
            }
            
            console.log('[WebClient] Normal action execution');
            // 正常执行 action
            return originalDoAction(action, options);
        };
        
        // 保存原始方法引用到新方法上
        this.actionService.doAction.__original = originalDoAction;
    },
    
    _getMenuNameByActionId(actionId) {
        // 尝试从菜单服务中查找对应的菜单项
        try {
            const menuService = this.env.services.menu;
            if (menuService && menuService.getAll) {
                const allMenus = menuService.getAll();
                // 只查找直接绑定该actionID的菜单（不考虑深度）
                const menusWithAction = allMenus.filter(menu => menu.actionID === actionId);
                
                if (menusWithAction.length === 0) {
                    return null;
                }
                
                // 如果有多个菜单绑定同一个action，选择最深层的（最具体的）
                let bestMenu = menusWithAction[0];
                let maxDepth = 0;
                
                for (const menu of menusWithAction) {
                    // 计算菜单深度（通过parent_id链）
                    let depth = 0;
                    let current = menu;
                    while (current.parent_id) {
                        depth++;
                        current = allMenus.find(m => m.id === current.parent_id);
                        if (!current) break;
                    }
                    
                    // 选择最深层的菜单
                    if (depth > maxDepth) {
                        maxDepth = depth;
                        bestMenu = menu;
                    }
                }
                
                console.log('[WebClient] Found menu for action', actionId, ':', bestMenu.name, 'depth:', maxDepth);
                return bestMenu.name;
            }
        } catch (e) {
            console.warn('[WebClient] Failed to get menu name:', e);
        }
        return null;
    },
    
    addTab(tabData) {
        console.log('[WebClient] addTab called:', tabData);
        // 检查是否已经有相同的标签页
        const actionKey = this._getActionKey(tabData.action);
        const existingTab = this.tabState.tabs.find(tab => 
            this._getActionKey(tab.action) === actionKey
        );
        
        if (existingTab) {
            console.log('[WebClient] Tab already exists, activating:', existingTab.id);
            this.tabState.activeTabId = existingTab.id;
            // 重新执行action以切换内容
            this._executeTabAction(existingTab);
        } else {
            console.log('[WebClient] Adding new tab:', tabData.id);
            this.tabState.tabs.push(tabData);
            this.tabState.activeTabId = tabData.id;
            console.log('[WebClient] Total tabs now:', this.tabState.tabs.length);
            
            // 执行 action
            this._executeTabAction(tabData);
        }
    },
    
    async _executeTabAction(tabData) {
        console.log('[WebClient] Executing action for tab:', tabData.id, 'action:', tabData.action);
        // 使用原始 doAction，但标记为内部调用
        const originalDoAction = this.actionService.doAction.__original || this.actionService.doAction;
        try {
            // 尝试更新顶部菜单栏的应用选择
            this._updateMenuForAction(tabData.action);
            
            // 添加 clearBreadcrumbs 选项以清除面包屑和历史记录，避免 URL 累积
            const options = {
                ...tabData.options,
                clearBreadcrumbs: true,  // 清除面包屑导航
            };
            
            await originalDoAction(tabData.action, options);
            console.log('[WebClient] Action executed successfully');
        } catch (error) {
            console.error('[WebClient] Error executing action:', error);
        }
    },
    
    _updateMenuForAction(actionId) {
        // 尝试根据action查找对应的菜单，并更新当前应用
        try {
            const menuService = this.env.services.menu;
            if (!menuService || !menuService.getAll) {
                return;
            }
            
            const allMenus = menuService.getAll();
            const targetMenu = allMenus.find(menu => menu.actionID === actionId);
            
            if (targetMenu) {
                // 查找根菜单（应用）
                let rootMenu = targetMenu;
                while (rootMenu.parent_id) {
                    const parent = allMenus.find(m => m.id === rootMenu.parent_id);
                    if (!parent) break;
                    rootMenu = parent;
                }
                
                // 如果找到根菜单且它是应用级别，切换到该应用
                if (rootMenu && !rootMenu.parent_id && menuService.setCurrentMenu) {
                    console.log('[WebClient] Switching to app:', rootMenu.name);
                    menuService.setCurrentMenu(rootMenu.id);
                }
            }
        } catch (e) {
            console.warn('[WebClient] Failed to update menu:', e);
        }
    },
    
    _getActionKey(action) {
        if (typeof action === 'object') {
            return JSON.stringify({
                type: action.type,
                res_model: action.res_model,
                res_id: action.res_id,
                view_mode: action.view_mode,
                xml_id: action.xml_id,
            });
        }
        return String(action);
    },
    
    closeTab(tabId, ev) {
        if (ev) {
            ev.stopPropagation();
        }
        
        const index = this.tabState.tabs.findIndex(tab => tab.id === tabId);
        if (index === -1) return;
        
        this.tabState.tabs.splice(index, 1);
        
        if (this.tabState.activeTabId === tabId) {
            if (this.tabState.tabs.length > 0) {
                const newIndex = Math.max(0, index - 1);
                this.tabState.activeTabId = this.tabState.tabs[newIndex].id;
            } else {
                this.tabState.activeTabId = null;
            }
        }
    },
    
    activateTab(tabId) {
        console.log('[WebClient] Activating tab:', tabId);
        const tab = this.tabState.tabs.find(t => t.id === tabId);
        if (!tab) {
            console.warn('[WebClient] Tab not found:', tabId);
            return;
        }
        
        // 更新激活标签
        this.tabState.activeTabId = tabId;
        
        // 重新执行该标签页的 action
        this._executeTabAction(tab);
    },
    
    isTabActive(tabId) {
        return this.tabState.activeTabId === tabId;
    },
});

